<?php

class Core_Tools {

	const INVALID_FILENAME_CHARS = "/[\"]/";

	/**
	 * creates dir if it doesn't exist.
	 * @param string $path - directory path (it's created recursively)
	 * @return boolean
	 */
	public static function createDir($path) {
		$path = preg_replace(self::INVALID_FILENAME_CHARS, "", $path);
		if (!is_dir($path)) {
			return mkdir($path, 0777, true);
		}
		return true;
	}
	
	public static function getFileExtension($filePath) {
		$path_parts = pathinfo($filePath);
		if (!isset($path_parts['extension']))
			return null;
		return '.' . $path_parts['extension'];
	}
	
	public static function getUserIpAddr() {
		if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
			return $_SERVER['HTTP_CLIENT_IP'];
		} else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			return $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
		}
	}
	
	public static function executeQuery($dbName, $sql) {
		$con = Propel::getConnection($dbName);
		$stmt = $con->prepare($sql);
		$stmt->execute();
		return $stmt->fetchAll(PDO::FETCH_ASSOC);
	}
	
	public static function ArrayToCSV($array, $header_row = true, $col_sep = ";", $row_sep = "\n", $qut = '"') {
		$output = null;
		if (!is_array($array) or !is_array($array[0]))
			return false;
	
		if ($header_row) {
			foreach ($array[0] as $key => $val) {
				$key = str_replace($qut, "$qut$qut", $key);
				$output .= "$col_sep$qut$key$qut";
			}
			$output = substr($output, 1) . "\n";
		}
		foreach ($array as $key => $val) {
			$tmp = '';
			foreach ($val as $cell_key => $cell_val) {
				if ($cell_val instanceof DateTime)
					$cell_val = $cell_val->format('Y-m-d H:i:s');
				$cell_val = str_replace($qut, "$qut$qut", $cell_val);
				$tmp .= "$col_sep$qut$cell_val$qut";
			}
			$output .= substr($tmp, 1) . $row_sep;
		}
		return $output;
	}
	
	public static function CsvToArray($csvDir, $headerRow=true, $colSep=";") {
		if (($handle = fopen($csvDir, "r")) !== FALSE) {
			$response = array();
			$first = true;
			while (($data = fgetcsv($handle, 1000, $colSep)) !== FALSE) {
				if ($first && $headerRow) {
					$first = false;
					$headers = array();
					foreach($data as $header) {
						$headers[] = $header;
					}
					continue;
				}
				$row = array();
				foreach ($data as $key => $value) {
					if ($headerRow)
						$row[$headers[$key]] = $value;
					else
						$row[] = $value;
				}
				$response[] = $row;
			}
			fclose($handle);
			return $response;
		}
		return false;
	}
	
}

?>